<script type="text/javascript">
/* <![CDATA[ */ 
//Global Variable from Server
var app_dir = "[##_APP_DIR_##]";

//give values to global variable flags 
flags = [##_DATA_TYPE_FLAGS_##];

myLinkURL = "[##_MY_LINK_URL_##]";

//Build up datatypes Array
var dataTypes  = [];
for(var flag in flags){
	var upperDataType = getTypeByFlag(flag);
	dataTypes[flag] = new DataType(flag, flags[flag], weights[upperDataType]);
}

//Build up a default callScenario and queue
var callScenario = [7,8,16,256,512,1024,2048,4096,16384,32768,65536,131072,262144,524288, 32,64,128,8192];
//var callScenario = [7,8,16,256,512,1024,2048,4096,16384,32768,65536,131072,262144,524288, 32,64,128,8192];
//var callScenario = [3,4,8,16,256,512,1024,2048,4096,16384,32768,65536,131072,262144,524288, 32,64,128,8192];

var queue = new Queue();
$.each(callScenario, function(index, value){
	queue.enqueue(value);
});

//Friends data
var friends;

//core data reservoir
var data = {
    "mode":0,
    "data":{},
	"error":0,
	"fail": 0
};

/*************************
 * Start Point
 *************************/
function getFriendsAJAX(){
    try{ 
	    $('.subtitle').show();
		$('.buttons_container').show();
	
	     graph.hide();
	    
	    $('#loading-box').html("Loading friends data").show();
	    
	    if (friends != undefined) {
	    
	        //onLoad Event Handler      
	        onFriendsDataLoaded();
	        
	    } else {
	            
	        $.getJSON(app_dir+'/ajax/getFriendsAJAX.php', null, function(data){
	
	            //check if there is an error
	            if(data.error != null){
	                if(confirm(data.error + "\nPress OK to try again")){
	                    getFriendsAJAX();                   
	                }
	            }else{
	            
	                //store data 
					friends = data;
	
	                //onLoad Event Handler              
	                onFriendsDataLoaded();
	                
	            }               
	        });
	    }        
	}catch(err){trace2(err);}
}

//maintain the current number of fetching process as MAX_CONCURRENT_FETCH_PROCESS
function invoke(){
    try {
		//check the current number of fetching process
		//if it's less than max number and the queue is not empty, go get it
		while (!queue.isEmpty() && currentNumberOfFetch < MAX_CONCURRENT_FETCH_PROCESS) {
			fetch();
		}
	}catch(err){trace2(err);}
}

//take an item from the queue and fetch data from the server 
function fetch(){
	
    try {
        if(!queue.isEmpty()) {

			var mode = queue.dequeue();

			if (mode != undefined) {
				//mask out flags which are already done
				mode = mode & (~ (data.mode & ~ data.error));
				//callXHR only when there is data needed to fetch
				if (mode) {
					callXHR(mode, function(response){

                        //make a chain
                        fetch();
					
                        //Post Process
						if (response.data != undefined) {
						
							//add to table
							table.addToHTMLTable(response);
							
							//add to graph
							if (isLoaded.applet) {
								graph.addToGraph(response);
							}
							
							//add to data
							data = concat(data, response);

							//loaded
							if (response.error != undefined) {
								mode = mode & (~ response.error);
								
								//retry
								retry(response.error);
							}
							
							//call handler
							onDataLoaded(mode);
							
						}
					});
				}
			}
		}
    }catch(err){trace2(err);}	
}

//add into the queue if only flags were tried less than 3 times
function retry(mode){

    try {
		//reset fail
		data.fail = data.fail & (~mode);
		
		var retryMode = 0;
		//get flags from mode
		for (var flag in dataTypes) {
			//check if the bit is set
			if ((mode & dataTypes[flag].flag) == dataTypes[flag].flag) {
				//only if retry times are less than maxRetry, enqueue
				if (dataTypes[flag].retry < maxRetry) {
					
					//increase number of retry
					dataTypes[flag].retry++;

                    //put it in the train
					retryMode = retryMode | dataTypes[flag].flag;
					
				} else {
					
					//fail and show retry icon
					fail(dataTypes[flag].name);
				}
			}
		}

        //just make the train start
		if(retryMode > 0){
			
            queue.enqueue(retryMode);
			invoke();			
		}
		
		
	}catch(err){trace2(err);}
}

function fail(flagName){

	try {
		
		//add it to the losers
		data.fail = data.fail | dataTypes[flagName].flag;
		
		//find upperDataType
        var upperDataType;
		for (var index in upperDataTypes) {
            if(flagName.toLowerCase().indexOf(upperDataTypes[index]) > -1){
				upperDataType = upperDataTypes[index];
			}
		}
		
		//show retry icon and bind click event handler which intend to make another go with error data
		$("<img src='./images/button_retry.gif' title='Click to retry fetching data'/>")
            .replaceAll('#span_'+upperDataType+' img')
			.css('cursor', 'pointer')
			.click(function(event){
			
				//show loading image again
				$("#span_"+upperDataType).html("<img src='./images/ajax-loader-small.gif'/> ");
				var mode = 0;
				
				//find failed dataType
				for(var flag in flags){

					//check if the datatype belongs to upperDataType(eg message), and also check if the datatype was failed
					if((flag.toLowerCase().indexOf(upperDataType) > -1) && ((flags[flag] & data.fail) == flags[flag])){

					  mode = mode | flags[flag];

					  //reset retry
					  dataTypes[flag].retry = 0;
					}
				}
				
				//go
				retry(mode);
			});

	}catch(err){trace2(err);}
}


/*
 * Data onLoad Event Handler
 */
function onDataLoaded(mode){

	try {
		
		/*
		 * Workaround: if the number of friends is not the same both on javascript and applet, just refresh!  
		 */
		if(isLoaded.applet){
			if(graph.getNumberOfFriends() != $(friends.data).length){
                graph.refresh();
			}
		}
		
		for(var flag in dataTypes){
			if((mode & dataTypes[flag].flag) == dataTypes[flag].flag){
				dataTypes[flag].isLoaded = true;
			} 
		}
		if (dataTypes['ONEWAY_MESSAGE_FLAG'].isLoaded && dataTypes['TWOWAY_MESSAGE_FLAG'].isLoaded) {
			$("<input id='chk_message' type='checkbox' name='chkbox_data' checked='checked'/>").replaceAll('#span_message').change(function(event){
				//set graph
				graph.setChecked("message", event.target.checked);
				
				//set table
                if (event.target.checked) {
                    $(".messagePoint")
					   .removeClass("disabled")
					   .addClass("enabled")
					   .css('color', normalColor);
                }
                else {
					
                    $(".messagePoint")
						.removeClass("enabled")
						.addClass("disabled")
						.css('color', disabledColor);
                }
				
				//Change table
				table.sumTotal();
				table.sort();
			});
			
		}
		
		if (dataTypes['MY_POST_FLAG'].isLoaded && dataTypes['FRIEND_POST_FLAG'].isLoaded) {
			if (document.getElementById('chk_post') == null) {
				$("<input id='chk_post' type='checkbox' name='chkbox_data' checked='checked'/>").replaceAll('#span_post').change(function(event){
					//set graph
					graph.setChecked("post", event.target.checked);
					
					//set table
	                if (event.target.checked) {
	                    $(".postPoint")
                            .removeClass("disabled")
                            .addClass("enabled")
                            .css('color', normalColor);
	                }
	                else {
	                    $(".postPoint")
							.removeClass("enabled")
	                        .addClass("disabled")
                            .css('color', disabledColor);
	                }
					
	                //Change table
	                table.sumTotal();
	                table.sort();
				});
			}
		}
		
		if (dataTypes['MY_COMMENT_ON_STATUS_FLAG'].isLoaded && dataTypes['MY_COMMENT_ON_LINK_FLAG'].isLoaded && dataTypes['MY_COMMENT_ON_NOTE_FLAG'].isLoaded && dataTypes['MY_COMMENT_ON_PHOTO_FLAG'].isLoaded &&
		dataTypes['FRIEND_COMMENT_ON_STATUS_FLAG'].isLoaded &&
		dataTypes['FRIEND_COMMENT_ON_LINK_FLAG'].isLoaded &&
		dataTypes['FRIEND_COMMENT_ON_NOTE_FLAG'].isLoaded &&
		dataTypes['FRIEND_COMMENT_ON_PHOTO_FLAG'].isLoaded) {
			if (document.getElementById('chk_comment') == null) {
				$("<input id='chk_comment' type='checkbox' name='chkbox_data' checked='checked'/>").replaceAll('#span_comment').change(function(event){
					//set graph
					graph.setChecked("comment", event.target.checked);
					
					//set table
                    if (event.target.checked) {
                        $(".commentPoint")
							.removeClass("disabled")
	                        .addClass("enabled")
							.css('color', normalColor);
                    }
                    else {
                        $(".commentPoint")
							.removeClass("enabled")
	                        .addClass("disabled")
							.css('color', disabledColor);
                    }
                    //Change table
                    table.sumTotal();
                    table.sort();
				});
			}
			
		}
		
		if (dataTypes['MY_LIKE_ON_STATUS_FLAG'].isLoaded && dataTypes['MY_LIKE_ON_LINK_FLAG'].isLoaded && dataTypes['MY_LIKE_ON_NOTE_FLAG'].isLoaded && dataTypes['MY_LIKE_ON_PHOTO_FLAG'].isLoaded &&
		dataTypes['FRIEND_LIKE_ON_STATUS_FLAG'].isLoaded &&
		dataTypes['FRIEND_LIKE_ON_LINK_FLAG'].isLoaded &&
		dataTypes['FRIEND_LIKE_ON_NOTE_FLAG'].isLoaded &&
		dataTypes['FRIEND_LIKE_ON_PHOTO_FLAG'].isLoaded) {
			if (document.getElementById('chk_like') == null) {
				$("<input id='chk_like' type='checkbox' name='chkbox_data' checked='checked'/>").replaceAll('#span_like').change(function(event){
					//set graph
					graph.setChecked("like", event.target.checked);
					
					//set table
                    if (event.target.checked) {
                        $(".likePoint")
                            .removeClass("disabled")
                            .addClass("enabled")
							.css('color', normalColor);
                    }
                    else {
                        $(".likePoint")
                            .removeClass("enabled")
                            .addClass("disabled")
							.css('color', disabledColor);
                    }
                    //Change table
                    table.sumTotal();
                    table.sort();
				});
			}
		}
	}catch(err){
		trace2(err);
	}
}

function onFriendsDataLoaded(){
    try {
		isLoaded.friend = true;
		
		//hide loading image
		$('#loading-box').hide();
		
		//Build Friend Table
		table.buildFriendTable(friends);
		
		//draw graph
		graph.draw();
		
		//when friend data is loaded, start ajax calls
		startLoadingData();
		
		//start 
        invoke();

	}catch(err){
		trace2(err);
    }
}

function onAppletLoaded(){
    try{
        isLoaded.applet = true;
        graph.draw();


        graph.show();
    }catch(err){trace2(err);}
}

/*
 * ETC functions
 */

function startLoadingData(){
	try {
		//show loading image
		$("span.datatype").html("<img src='./images/ajax-loader-small.gif'/> ");
		
		//show progress text
		showProgress()
		
	}catch(err){trace2(err);}
}

function linkToFriendshipPage(id){
	try {
//		var url = "/-friends/friendship.php?fId=" + id;
//		if (confirm("Do you want to go to the friendship page?")) {
//			window.location.href = url;
//		}
        var url = $('#'+id +' a').attr('href');
        window.open(url);
		
	}catch(err){trace2(err);}
}

function checkUp(){
	try{
		if(!isLoaded.applet){
			if (graph.checkUp()) {
                setTimeout("onAppletLoaded()", 2000);			
			}else{
				setTimeout("checkUp()", 1000);
			}
		}
	}catch(err){trace2(err);}
}

function showProgress(){
    try {
		var total = callScenario.length;
		var remaining = queue.size();
		var timeout;
		
		//show message
		var msg = "Processing data : " + (total - remaining) + " of " + total;
		$('#progress_status').text(msg).fadeOut();
		if (remaining > 0) {
			$('#progress_status').fadeIn();
			timeout = setTimeout("showProgress()", 1000);
		}
		else {
			$('#progress_status').text(msg).empty();
		}
	}catch(err){trace2(err);}
}

/*  
 * From Applet to Javascript, set max to slider from applet
 */
function setMaxScore(maxScore){
	try {
		$('#max_score_label').text(maxScore);
		if (maxScore > 0) {
			$('#slider').slider("option", "max", maxScore);
		}
	}catch(err){trace2(err);}
}


//on document ready
$(document).ready(function(){
	
	
    /************************************************
     * UI  : slider, dialog, button, accordion, etc
     ************************************************/

    //Filtering Slider
    $('#threshold').val(default_threshold);
    $('#slider').slider({
        slide: function(event,ui){
            $('#threshold').val(ui.value);
        },
        change: function(event, ui){
            threshold = ui.value;
            graph.setThreshold(threshold);
            table.filtering(threshold);
        }
    });
	
    $('#message_weight_label').text(weights.message);
    $('#message_weight_slider').slider({
        max: 5,
        value: weights.message,
        slide: function(event, ui){
            $('#message_weight_label').text(ui.value);
        },
        change: function(event, ui){
            weights.message = ui.value;
            graph.setMessageWeight(ui.value);
            table.rebuildFriendTable(data);
        }
    });
    
    $('#post_weight_label').text(weights.post);
    $('#post_weight_slider').slider({
        max: 5,
        value: weights.post,
        slide: function(event, ui){
            $('#post_weight_label').text(ui.value);
        },
        change: function(event, ui){
            weights.post = ui.value;
            graph.setPostWeight(ui.value);
            table.rebuildFriendTable(data);
        }
    });
    $('#comment_weight_label').text(weights.comment);
    $('#comment_weight_slider').slider({
        max: 5,
        value: weights.comment,
        slide: function(event,ui){
            $('#comment_weight_label').text(ui.value);
        },
        change: function(event, ui){
            weights.comment = ui.value;
            graph.setCommentWeight(ui.value);
            table.rebuildFriendTable(data);
        }
    });
    $('#like_weight_label').text(weights.like);
    $('#like_weight_slider').slider({
        max: 5,
        value: weights.like,
        slide: function(event,ui){
            $('#like_weight_label').text(ui.value);
        },
        change: function(event, ui){
            weights.like = ui.value;
            graph.setLikeWeight(ui.value);
            table.rebuildFriendTable(data);
        }
    });

    var friendDialog = $('#friend-container').dialog({
        autoOpen: false,
        width: 400, 
        height: 270,
        position: [300, 300],
        show: 'fade',
        hide: 'fade',
        open: function(event, ui){
            shadowyIFrame("friend", $(this).parent());
        },
        drag: function(event, ui){
            $('#friend')
                .css('left', ui.position.left)
                .css('top', ui.position.top);
        },
        resize: function(event, ui){
            $('#friend')
                .css('left', ui.position.left)
                .css('top' , ui.position.top)
                .width($(this).parent().outerWidth())
                .height($(this).parent().outerHeight());
        },
        close: function(event, ui){
            $('#friend').remove();
        }
    });   
 

    //Accordion
    $('.switchboard').accordion({
        collapsible: true
    });

    //settings dialog
    var settingDialog = $('#settings-container').dialog({
        autoOpen: false,
        resizable: false,
        width: 430, 
        height: 190,
        position: ['center', 400],
        show: 'fade',
        hide: 'fade',
        open: function(event, ui){
            shadowyIFrame("settingsShim", $(this).parent());
        },
        drag: function(event, ui){
            $('#settingsShim')
                .css('left', ui.position.left)
                .css('top', ui.position.top);
        },
        resize: function(event, ui){
            $('#settingsShim')
                .css('left', ui.position.left)
                .css('top' , ui.position.top)
                .width($(this).parent().outerWidth())
                .height($(this).parent().outerHeight());
        },
        close: function(event, ui){
            $('#settingsShim').remove();
        }       
    });
 
    $('#show_friend_table_button')
       .button()
       .click(function(){
            if(friendDialog.dialog("isOpen")){
                friendDialog.dialog("close");
            }else{
                friendDialog.dialog("open");
            }
            return false;
        });
    
    $('#show_settings_button')
       .button({
            icons: {
                primary: "ui-icon-gear"
            }
        })
       .click(function(){
            if(settingDialog.dialog("isOpen")){
                settingDialog.dialog("close");
            }else{
                settingDialog.dialog("open");
            }
            return false;
        });


    //show announcement
    var announcement;
    $.get(app_dir+'/template/announcement.html',null,function(response){
        announcement = $(response)
        .appendTo('body')
        .dialog({
            title: "Welcome!",
            resizable: true,
            width: 370, 
            height: 443,
            position: ['center', 'center'],
            show : 'fade',
            hide : 'fade',
            open: function(event, ui){
                shadowyIFrame("announ_shadow", $(this).parent());
            },
            drag: function(event, ui){
                $('#announ_shadow')
                  .css('left', ui.position.left)
                  .css('top', ui.position.top);
            },
            resize: function(event, ui){
                $('#announ_shadow')
                  .css('left', ui.position.left)
                  .css('top' , ui.position.top)
                  .width($(this).parent().outerWidth())
                  .height($(this).parent().outerHeight());
            },
            close: function(event, ui){
                $('#announ_shadow').remove();
            }       
        });
    }); 
    
    $('#about_button')
    .button({
        icons: {
            primary: "ui-icon-help"
        },
        text: false
    })
    .click(function(){
        if(announcement.dialog("isOpen")){
            announcement.dialog("close");
        }else{
            announcement.dialog("open");
        }
        return false;
    }); 
	
	$('#refresh_button')
    .button({
        icons: {
            primary: "ui-icon-arrowrefresh-1-s"
        },
        text: false
    })
    .click(function(){
        graph.refresh();
        return false;
    }); 
		
	//Invoke AJAX requests
    if("[##_EXIST_SESSION_##]"){
		
		//start ajax requests
		getFriendsAJAX();
		
		//check if applet is loaded 
		checkUp();
		
	}
	
});



/* ]]> */
</script>
